﻿using System;
using System.Collections.Generic;
using System.Linq;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.Abstractions;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.ModelBinders;
using RoketSolutions.SP2010.Infrostructure.UI.Ajax.ValueProviders;

namespace RoketSolutions.SP2010.Infrostructure.UI.Ajax.Controllers
{
    public class ControllerFactory
    {
        public ControllerFactory(IEnumerable<ControllerBase> controllers, ModelBinderDictionary modelBinders, ValueProviderFactoryCollection valueProviderFactories)
        {
            if (controllers == null)
                throw new ArgumentNullException("controllers");

            Controllers = controllers.ToDictionary(item => item.GetType().Name);
            ModelBinders = modelBinders;
            ValueProviders = valueProviderFactories;
        }

        protected Dictionary<string, ControllerBase> Controllers
        {
            get; private set;
        }

        protected ModelBinderDictionary ModelBinders
        {
            get;
            set;
        }

        protected ValueProviderFactoryCollection ValueProviders
        {
            get;
            set;
        }

        public virtual ControllerBase CreateController(RequestContext requestContext)
        {
            var controllerName = string.Format("{0}Controller", requestContext.ControllerName);
            var controller = Controllers[controllerName];
            if (controller != null)
            {
                controller.ModelBinders = ModelBinders;
                controller.ValueProviders = ValueProviders;
            }
            return controller;
        }

    }
}